package com.jueling.culture.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jueling.culture.core.Result;
import com.jueling.culture.core.ResultGenerator;
import com.jueling.culture.core.service.TokenManageService;
import com.jueling.culture.dto.req.LoginVO;
import com.jueling.culture.dto.req.UserPasswordVO;
import com.jueling.culture.dto.res.BackstageUserDto;
import com.jueling.culture.dto.res.EditBackstageUserDto;
import com.jueling.culture.exception.FrontShowException;
import com.jueling.culture.model.UserInfo;
import com.jueling.culture.service.AgentInfoService;
import com.jueling.culture.service.UserInfoService;
import com.jueling.culture.support.annotation.RequiredPermission;
import com.jueling.culture.support.enums.AuthorityCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 人员管理
 * @author linp
 * @create 2022/4/8 15:11
 */
@RestController
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private TokenManageService tokenManageService;

    @Autowired
    private AgentInfoService agentInfoService;

    /**
     * admin用的id
     */
    private static final Integer ADMIN_ID = 1;

    /**
     * 用户列表
     * @param pageIndex
     * @param pageSize
     * @param keywords
     * @return
     */
    @GetMapping("/api/user")
    @RequiredPermission(authorityCodeEnum = AuthorityCodeEnum.SYSTEM_USER_MANAGE, view = true)
    public Result list(@RequestParam(defaultValue = "0") Integer pageIndex, @RequestParam(defaultValue = "0") Integer pageSize, String keywords) {
        PageHelper.startPage(pageIndex, pageSize);
        List<UserInfo> list = userInfoService.getUserList(keywords);
        PageInfo<UserInfo> pageInfo = new PageInfo<>(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    /**
     * 新增用户
     * @param backstageUserDto
     * @return
     */
    @PostMapping("/api/user")
    @RequiredPermission(authorityCodeEnum = AuthorityCodeEnum.SYSTEM_USER_MANAGE, edit = true)
    public Result add(@RequestBody BackstageUserDto backstageUserDto) {
        if (backstageUserDto.getPassword().equals(backstageUserDto.getName())) {
            throw new FrontShowException("密码设置不可与账号相同");
        }
        //密码加密
        backstageUserDto.setPassword(BackstageUserDto.getMD5Password(backstageUserDto.getUserName(), backstageUserDto.getPassword()));
        userInfoService.addBackstageUser(backstageUserDto);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/api/user/{id}")
    @RequiredPermission(authorityCodeEnum = AuthorityCodeEnum.SYSTEM_USER_MANAGE, edit = true)
    public Result delete(@PathVariable String id) {
        if (id.equals(ADMIN_ID)) {
            throw new FrontShowException("系统用户不允许删除");
        }
        userInfoService.deleteByUserId(id);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 编辑用户
     * @param id
     * @param editBackstageUserDto
     * @return
     */
    @PutMapping("/api/user/{id}")
    @RequiredPermission(authorityCodeEnum = AuthorityCodeEnum.SYSTEM_USER_MANAGE, edit = true)
    public Result update(@PathVariable String id, @RequestBody EditBackstageUserDto editBackstageUserDto) {
        if (id.equals(ADMIN_ID)) {
            throw new FrontShowException("系统用户不允许编辑");
        }
        userInfoService.updateBackstageUser(id, editBackstageUserDto);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 修改当前用户密码
     * @param userPasswordVO
     * @return
     */
    @PutMapping("/api/user/update/pwd")
    public Result updatePassword(@RequestBody UserPasswordVO userPasswordVO) {
        UserInfo currentUser= UserInfo.currentUser.get();

        String userName=currentUser.getUserName();
        if (userPasswordVO.getOldPassword()!=null) {
            String md5Password= UserInfo.getMD5Password(userName,userPasswordVO.getOldPassword());
            UserInfo backstageUserInfo=userInfoService.login(userName,md5Password);
            if (backstageUserInfo == null) {
                throw new FrontShowException("旧密码错误");
            }
        }
        if (userPasswordVO.getPassword().equals(userName)) {
            throw new FrontShowException("密码设置不可与账号相同");
        }
        userInfoService.resetPassword(currentUser.getUserId(), UserInfo.getMD5Password(userName, userPasswordVO.getPassword()));
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 重置用户密码
     * @param userId
     * @param userNamePasswordLoginDTO
     * @return
     */
    @PutMapping("/api/user/ps/{userId}")
    @RequiredPermission(authorityCodeEnum = AuthorityCodeEnum.SYSTEM_USER_MANAGE, edit = true)
    public Result resetPassword(@PathVariable String userId, @RequestBody LoginVO userNamePasswordLoginDTO) {

        if (userNamePasswordLoginDTO.getPassword().equals(userNamePasswordLoginDTO.getUserName())) {
            throw new FrontShowException("密码设置不可与账号相同");
        }
        userInfoService.resetPassword(userId, UserInfo.getMD5Password(userNamePasswordLoginDTO.getUserName(), userNamePasswordLoginDTO.getPassword()));
        //清除token
        UserInfo userInfo = userInfoService.findByIds(userId + "").get(0);
        tokenManageService.deleteTokenByUserId(userInfo.getUserName());
        return ResultGenerator.genSuccessResult();
    }



    /**
     * 判断用户名是否存在
     * @param userName
     * @return
     */
    @GetMapping("/api/check/user/{userName}")
    @RequiredPermission(authorityCodeEnum = AuthorityCodeEnum.SYSTEM_USER_MANAGE, view = true)
    public Result checkUser(@PathVariable String userName) {
        Boolean check = userInfoService.checkUser(userName);
        return ResultGenerator.genSuccessResult(check);
    }

    /**
     * 获取代理人树-级连
     * @return
     */
    @GetMapping("/api/get/agent/user/hover")
    @RequiredPermission(authorityCodeEnum = AuthorityCodeEnum.SYSTEM_USER_MANAGE, view = true)
    public Result getAgentUserListForHover() {
        return ResultGenerator.genSuccessResult(agentInfoService.getAgentUserListForHover());
    }


}
